package com.woniuxy.java102vuecli.service.impl;

import com.woniuxy.java102vuecli.entity.Menu;
import com.woniuxy.java102vuecli.entity.Role;
import com.woniuxy.java102vuecli.exception.MenuReferenceException;
import com.woniuxy.java102vuecli.mapper.MenuMapper;
import com.woniuxy.java102vuecli.mapper.RoleMapper;
import com.woniuxy.java102vuecli.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author author
 * @Create 2023-10-08 9:55
 */
@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    MenuMapper menuMapper;

    @Autowired
    RoleMapper roleMapper;

    @Override
    public List<Menu> getAllMenus() {
        List<Menu> allmenus = menuMapper.selectAllMenus();
        List<Menu> menus = allmenus
                .stream()
                .filter(menu -> menu.getPmid().equals(0))
                .map(menu -> {
                    //对一级菜单添加children属性
                    List<Menu> children=allmenus.stream()
                            .filter(submenu->submenu.getPmid().equals(menu.getMid()))
                            .collect(Collectors.toList());
                    menu.setChildren(children);
                    return menu;
                })
                .collect(Collectors.toList());
        return menus;
    }

    @Override
    public void removeMenuByMid(int mid) {
        //被引用的不能删除
        List<Role> roles = roleMapper.selectRolesByMid(mid);
        if(roles.size()!=0){
            throw new MenuReferenceException("菜单被使用");
        }
        //TODO:Mapper物理删除?逻辑删除?
    }

    @Override
    public List<Menu> getMenusByEid(int eid) {
        List<Menu> allmenus = menuMapper.selectMenusByEid(eid);
        List<Menu> menus = allmenus
                .stream()
                //筛选一级菜单
                .filter(menu -> menu.getPmid().equals(0))
                .map(menu -> {
                    //对一级菜单添加children属性
                    menu.setChildren(allmenus.stream()
                            .filter(submenu->submenu.getPmid().equals(menu.getMid()))
                            .collect(Collectors.toList()));
                    return menu;
                })
                .collect(Collectors.toList());
        return menus;
        //Stream改写
//        List<Menu> menus = new ArrayList<>();
//        for(Menu menu : allmenus){
//            if(menu.getPmid()==0){
//                menus.add(menu);
//                for(Menu submenu : allmenus){
//                    if(submenu.getPmid().equals(menu.getMid())){
//                        menu.getChildren().add(submenu);
//                    }
//                }
//            }
//        }
    }
}
